package com.pvms.demo;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import ucar.ma2.Array;
import ucar.ma2.Index;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;

import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        String ncFilePath = "D:\\ws\\soft\\project\\soft\\java\\ncfile_reader\\src\\main\\resources\\题三附件_NMC_HENAN_RH-AVG_L2M_G005_20240312000000_H24_H1.NC"; // 替换为实际的NC文件路径
        String excelFilePath = "result.xlsx"; // 生成的Excel文件路径
       NetcdfFile ncFile = NetcdfFile.open(ncFilePath);
            // 获取经度变量
            Variable lonVar = ncFile.findVariable("lon"); // 假设经度变量名为lon
            Array lonArray = lonVar.read();
            // 获取纬度变量
            Variable latVar = ncFile.findVariable("lat"); // 假设纬度变量名为lat
            Array latArray = latVar.read();
            // 获取温度数值变量
            Variable dataVar = ncFile.findVariable("temperature"); // 假设温度变量名为temperature
            Array dataArray = dataVar.read();

            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("Data");
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("Longitude");
            headerRow.createCell(1).setCellValue("Latitude");
            headerRow.createCell(2).setCellValue("Value");

            Index dataIndex = dataArray.getIndex();
            for (int i = 0; i < dataArray.getSize(); i++) {
                dataIndex.set(i);
                double value = dataArray.getDouble(dataIndex);
                int[] coords = dataIndex.getCurrentCounter();
                int lonIndex = coords[0]; // 假设经度维度在第0维
                int latIndex = coords[1]; // 假设纬度维度在第1维
                double lon = lonArray.getDouble(lonIndex);
                double lat = latArray.getDouble(latIndex);

                Row row = sheet.createRow(i + 1);
                Cell lonCell = row.createCell(0);
                lonCell.setCellValue(lon);
                Cell latCell = row.createCell(1);
                latCell.setCellValue(lat);
                Cell valueCell = row.createCell(2);
                valueCell.setCellValue(value);
            }

            try (FileOutputStream outputStream = new FileOutputStream(excelFilePath)) {
                workbook.write(outputStream);
            }
            System.out.println("Excel file generated successfully at: " + excelFilePath);

    }
}